﻿// RestartManager.cpp
#include "RestartManager.h"
#include <QApplication>
#include <QTimer>

RestartManager::RestartManager(QObject *parent)
    : QObject(parent)
{
}

void RestartManager::restart()
{
    performRestart();
}

void RestartManager::delayedRestart(int delayMs)
{
    QTimer::singleShot(delayMs, []() {
        performRestart();
    });
}

void RestartManager::restartWithArgs(const QStringList &newArgs)
{
    performRestart(newArgs);
}

QStringList RestartManager::currentArguments()
{
    return QCoreApplication::arguments();
}

QString RestartManager::applicationFilePath()
{
    return QCoreApplication::applicationFilePath();
}

void RestartManager::performRestart(const QStringList &args)
{
    QStringList restartArgs;

    if (args.isEmpty()) {
        // 使用当前参数
        restartArgs = QCoreApplication::arguments();
        restartArgs.removeFirst(); // 移除程序路径
    } else {
        // 使用新参数
        restartArgs = args;
    }

    QString program = QCoreApplication::applicationFilePath();

    // 发出信号通知即将重启
    emit RestartManager::instance()->aboutToRestart();

    // 启动新进程
    QProcess::startDetached(program, restartArgs);

    // 退出当前进程
    // QCoreApplication::exit(0);
    qApp->quit();
}

// 单例实例
RestartManager* RestartManager::instance()
{
    static RestartManager manager;
    return &manager;
}
